package org.jash.mvp2206.news;

import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.jash.mvp2206.R;
import org.jash.mvp2206.entity.NewsPage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class NewsAdapter extends BaseAdapter {
    private List<NewsPage.DataBean.RecordsBean> data = new ArrayList<>();
    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public NewsPage.DataBean.RecordsBean getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return getItem(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
            convertView.setTag(new NewsViewHolder(convertView));
        }
        NewsViewHolder holder = (NewsViewHolder) convertView.getTag();
        NewsPage.DataBean.RecordsBean bean = data.get(position);
        Glide.with(holder.image)
                .load(bean.getImgurl())
                .into(holder.image);
        holder.title.setText(bean.getTitle());
        holder.time.setText(bean.getCreateTime());
        return convertView;
    }

    public void addAll(Collection<? extends NewsPage.DataBean.RecordsBean> collection) {
        data.addAll(collection);
        notifyDataSetChanged();
    }

    public void clear() {
        data.clear();
        notifyDataSetChanged();
    }

    public static class NewsViewHolder {
        private ImageView image;
        private TextView title;
        private TextView time;
        public NewsViewHolder(View itemView) {
            image = itemView.findViewById(R.id.image);
            title = itemView.findViewById(R.id.title);
            time = itemView.findViewById(R.id.time);
        }
    }
}
